﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SysFrame.BP;
using SysFrame.Message;
using UpdataByExcel;

namespace AppServer.Controllers.System
{
    [Route("api/[controller]")]
    [ApiController]
    public class System1Controller : SysControllerBase
    {

        private IHostingEnvironment hostingEnv;

        public System1Controller(IHostingEnvironment env)
        {
            this.hostingEnv = env;
        }

        //功能
        // POST: api/System6
        [HttpPost]
        public ActionResult<string> Post([FromBody] dynamic data)
        {
            string jsTimeStamp = data.jsTimeStamp;
            string Action = data.Action == null ? "Get" : data.Action;
            string rtstr = "";
            //得到列表
            if (Action == "Get")
            {
                rtstr = Get(data);
            }
            if (Action == "Save")
            {
                rtstr = Save(data);
            }
            if (Action == "Login")
            {
                rtstr = Login(data);
            }
            if (Action == "GetBtnPermission")
            {
                rtstr = GetBtnPermission(data);
            }
            if (Action == "ButtonLog")
            {
                rtstr = ButtonLog(data);
            }
            if (Action == "ClickMenuLog")
            {
                rtstr = ClickMenuLog(data);
            }
            return rtstr;
        }

        //用户上传excel
        // POST: api/System1
        [HttpPost("upload")]
        public ActionResult<string> Post(IFormCollection form)
        {
             string result = "";
             string webRootPath = hostingEnv.WebRootPath;
             string contentRootPath = hostingEnv.ContentRootPath;
 
             FormFileCollection filelist = (FormFileCollection)form.Files;

            foreach (IFormFile file in filelist)
            {
                try
                {
                    String Tpath = "/sys1file" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                    string name = file.FileName;
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string FilePath = webRootPath + Tpath;

                    string type = Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);


                    if (!di.Exists) { di.Create(); }


                    using (FileStream fssave = new FileStream(FilePath + FileName + type, FileMode.Create))
                    {
                        // 复制文件
                        file.CopyTo(fssave);
                        // 清空缓冲区数据
                        fssave.Flush();
                    }
                    //FileStream fs = new FileStream(FilePath + FileName + type, FileMode.OpenOrCreate);
                    DataTable dt = NPOIHelper.RenderDataTableFromExcel(FilePath + FileName + type, type, 0, 0);
                    result = "1";
                }
                catch(Exception ex) { }
            }
            //form["data"]
            return form.Files[0].FileName;

            //return file.FileName;
        }


        //用户下载excel
        // POST: api/System1
        [HttpGet("downExcel")]
        public ActionResult Get()
        {
            List<string> list = new List<string>();
            string js = string.Join(';', list);
            var filePath = hostingEnv.WebRootPath + "/file/TestData_2.xlsx";
            
            var fileName = "项目原型.xlsx";
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            fs.Close();
            return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", fileName);
        }


        /// <summary>
        /// 得到用户列表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Get(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            string search = postdata["search"].ToString();
            string notuid = postdata["notuid"].ToString();
            BLLsystem_1 bll = new BLLsystem_1();
            List<Mssystem_1> mssys1 = new List<Mssystem_1>();
            MsQuery msq = new MsQuery();
            if (!string.IsNullOrEmpty(search))
            {
                msq.strquery += " and (System_1_20 like '%" + search + "%' ";
                msq.strquery += " or System_1_40 like '%" + search + "%' ";
                msq.strquery += " or System_1_120 like '%" + search + "%' ";
                msq.strquery += " or System_1_140 like '%" + search + "%' ";
                msq.strquery += " )"; 
            }
            if (string.IsNullOrEmpty(notuid))
            {
                notuid = "-1";
            }
            notuid += ",1";
            msq.strquery += " and SYSTEM_1_10 not in (" + notuid + ") ";
            mssys1 = bll.Getsystem_1MsByQuery(msq);
            return JArray.FromObject(mssys1).ToString();
        }

        /// <summary>
        /// ButtonLog
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ButtonLog(dynamic data)
        {
            string res = "";
            Task.Run(() =>
            {
                JObject datajson = JObject.FromObject(data);
                JObject postdata = JObject.FromObject(data.data);
                string btnid = postdata["btnid"].ToString();
                string MenuId = datajson["MenuId"].ToString();
                //Mssystem_1 lodeuser = GetSessionUser();
                string value = GetSession("LoginUser");
                Mssystem_1 lodeuser = Mssystem_1.parse(value);
                MsReturned msr = new MsReturned();
                BLLsystem_16.ButtonLog(lodeuser.System_1_10.ToString(), MenuId, btnid);
                //res = JObject.FromObject(msr).ToString();
            });
            return res;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ClickMenuLog(dynamic data)
        {
            string res = "";
            Task.Run(() =>
            {
                JObject datajson = JObject.FromObject(data);
                string MenuId = datajson["MenuId"].ToString();
                //Mssystem_1 lodeuser = GetSessionUser();
                string value = GetSession("LoginUser");
                Mssystem_1 lodeuser = Mssystem_1.parse(value);
                MsReturned msr = new MsReturned();
                BLLsystem_16.ClickMenuLog(lodeuser.System_1_10.ToString(), MenuId);
                //res = JObject.FromObject(msr).ToString();
            });
            return res;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Save(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            string userdata = postdata["data"].ToString();
            Mssystem_1 ms = Mssystem_1.parse(userdata);
            string res = "";
            MsReturned msr = new MsReturned();
            msr = new BLLsystem_1().Savesystem_1(ms);
            res = JObject.FromObject(msr).ToString();
            return res;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Login(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            string username = postdata["username"].ToString();
            string psw = postdata["psw"].ToString();
            string res = "";
            MsReturned msr = new MsReturned();
            if (string.IsNullOrEmpty(username))
            {
                res = "请输入用户名";
                return res;
            }
            if (string.IsNullOrEmpty(psw))
            {
                res = "请输入密码";
                return res;
            }
            BLLsystem_1 bll = new BLLsystem_1();
            MsReturned ms = new MsReturned();
            ms = bll.UserLode(username, psw);
            switch (ms.strMsId)
            {
                case "-1":
                    res = "用户名不存在";
                    break;
                case "-2":
                    res = "用户名或密码错误";
                    break;
                case "1":
                    msr.strMsId = "1";
                    Mssystem_1 ms1 = (Mssystem_1)ms.obj1;
                    string sys1 = JObject.Parse("{'System_1_10':"+ ms1.System_1_10+ ",'menuids':["+ ms1.menuids+ "]}").ToString();
                    msr.data = EncryptDES.strEncryptToDES(sys1);
                    res = "登录成功";
                    break;
                default:
                    break;
            }
            msr.strMS = res;
            return JObject.FromObject(msr).ToString();
        }

        /// <summary>
        /// 得到按钮
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string GetBtnPermission(dynamic data)
        {
            JObject postdata = JObject.FromObject(data.data);
            string MenuId = postdata["MenuId"].ToString();
            Mssystem_1 lodeuser = GetSessionUser();
            List<string> btnids = BLLsystem_1.GetUserBtnByMenu(lodeuser.sys10.System_10_10, MenuId, true);
            if (lodeuser.isadmin) {
                btnids = BLLsystem_1.GetAllBtnByMenu(MenuId);
            }
            string res = JArray.FromObject(btnids).ToString(); ;
            return res;
        }
    }
}